package net.huashitong.synthetical.newSupervision.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.dao.SysUserDao;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.sys.util.SysUserUtils;
import net.huashitong.synthetical.newSupervision.dao.TaskBackDao;
import net.huashitong.synthetical.newSupervision.dao.TaskNewDao;
import net.huashitong.synthetical.newSupervision.dao.TaskWorkableDao;
import net.huashitong.synthetical.newSupervision.entity.*;
import net.huashitong.synthetical.newSupervision.dao.TaskSendDao;
import net.huashitong.synthetical.newSupervision.filter.TaskMessageFilter;
import net.huashitong.synthetical.newSupervision.filter.TaskNewFilter;
import net.huashitong.synthetical.newSupervision.filter.TaskSendFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/7/2
 * Time: 20:47
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Service

public class TaskSendService extends StringPKService<TaskSend> {

    @Autowired
    private TaskSendDao dao;

    @Autowired
    private TaskNewDao taskNewDao;
    @Autowired
    private SysUserDao userDao;
    @Autowired
    private TaskWorkableService taskWorkableService;
    @Autowired
    private TaskLogService taskLogService;
    @Autowired
    private SysTableService tableService;

    @Autowired
    private TaskMessageService taskMessageService;

    @Autowired
    private TaskBackService taskBackService;

    SimpleDateFormat simdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    protected void beforeSave(TaskSend obj) {
        obj.setSysId(tableService.updateMaxSysId("t_task_send", null));
    }

    @Override
    protected BaseDao<TaskSend, String> getDao() {
        return this.dao;
    }

    public List<TaskSend> queryByUserId(String userId) {
        return dao.queryByUserId(userId);
    }

    public List<TaskSend> queryByTaskId(String taskId) {
        return dao.queryByTaskId(taskId);
    }

    public void deleteByTaskIds(List<String> taskIds) {
        dao.batchDeleteTaskIds(taskIds);
    }

    public List<TaskSend> queryByTaskIdAndType(String taskId, String type) {
        return dao.queryByTaskIdAndType(taskId, type);
    }

    /**
     * 条件查询
     *
     * @param filter
     * @return
     */
    public List<TaskNew> queryFilter(TaskNewFilter filter) {
        return dao.queryFilter(filter);
    }


    /**
     * 签收批转任务保存
     *
     * @param filter
     * @return
     */
    public String updateSign(TaskSendFilter filter) {
        String sysId = filter.getSysId();
        String taskId = filter.getTaskId();
        List<TaskWorkable> list = filter.getList();
        if (list != null && !list.isEmpty()) {


            TaskSend taskSend = dao.getById(sysId);
            taskSend.setType("1");
            dao.update(taskSend);

            //任务流程记录
            TaskLog taskLog = new TaskLog();
            taskLog.setProcesses("承办单位签收");
            taskLog.setTableId(taskId);
            SysUser user = userDao.getById(taskSend.getUserId());
            taskLog.setTransactor(taskSend.getDepartName() + user.getName());
            taskLog.setTransactorTel(user.getMobile());
            String datetime = simdate.format(new Date());
            taskLog.setDatetime(datetime);
            taskLogService.save(taskLog);


            for (TaskWorkable taskWorkable : list) {
                if (StringUtils.isBlank(taskWorkable.getOperatorId())) {
                    continue;
                }
                taskWorkable.setSendId(sysId);
                taskWorkable.setTaskId(taskId);
                taskWorkableService.save(taskWorkable);

                //任务流程记录
                TaskLog taskLog2 = new TaskLog();
                taskLog2.setProcesses("承办单位指定经办人");
                taskLog2.setTableId(taskId);
                taskLog2.setTransactor(taskWorkable.getOperator());
                taskLog2.setTransactorTel(taskWorkable.getOperatorTel());
                taskLog2.setDatetime(simdate.format(new Date()));
                taskLogService.save(taskLog2);

            }


            //保存完后判断当前任务下的所有派发是否都已经签收
            //当前任务下派发的任务状态都是未签收的send没有数据,表示都已签收,改变主任务的type
            List<TaskSend> sendList = dao.queryByTaskIdAndType(taskId, "1");
            if (sendList.size() <= 0) {
                TaskNew taskNew = taskNewDao.getById(taskId);
                taskNew.setType("1");
                taskNewDao.update(taskNew);
            }
            return "200";
        }
        return "没有添加批转人员!";
    }

    /**
     * 添加撤销协调申请
     *
     * @param message
     * @return
     */
    public String saveRepeal(TaskMessage message) {
        TaskSend send = dao.getById(message.getSendId());
        message.setType("2");  //设置消息类型为申请撤销
        message.setTaskId(send.getTaskId());
        message.setSenderId(SysUserUtils.getUserId());//设置申请人id
        //设置消息接收人id,即创建任务人id
        message.setAccepterId(taskNewDao.getById(send.getTaskId()).getCreateUser());
        message.setSendId(message.getSendId());
        message.setSendDeptName(send.getDepartName());
        message.setState("0");//未读
        taskMessageService.save(message);

        //任务流程记录
        SysUser user = userDao.getById(send.getUserId());
        TaskLog taskLog = new TaskLog();
        taskLog.setProcesses("申请撤销任务");
        taskLog.setTableId(message.getTaskId());
        taskLog.setTransactor(send.getDepartName() + user.getName());
        taskLog.setTransactorTel(user.getMobile());
        taskLog.setDatetime(simdate.format(new Date()));
        taskLogService.save(taskLog);
        return "200";
    }


    /**
     * 协调单位
     *
     * @param filter
     * @return
     */
    public String saveDispose(TaskMessageFilter filter) {
        if (filter.getList().size() > 0) {
            TaskNew taskNew = taskNewDao.getById(filter.getTaskId());
            for (TaskSend taskSend : filter.getList()) {
                if (com.sirdc.modules.utils.StringUtils.isNotBlank(taskSend.getUserId())) {
                    taskSend.setDateTime(taskNew.getDateTime());
                    taskSend.setTaskId(filter.getTaskId());
                    // 任务状态
                    taskSend.setType("0");
                    // 数据有效性
                    taskSend.setStatus("1");
                }
            }

            String createUser = taskNew.getCreateUser();
            SysUser user = userDao.getById(createUser);
            //任务流程记录
            TaskLog taskLog = new TaskLog();
            taskLog.setProcesses("协调任务单位");
            taskLog.setTableId(filter.getTaskId());
            taskLog.setTransactor(user.getName());
            taskLog.setTransactorTel(user.getMobile());
            taskLog.setDatetime(simdate.format(new Date()));
            taskLogService.save(taskLog);
            return "200";
        } else {
            return null;
        }
    }

    /**
     * 撤销单位
     *
     * @param id 派发单位id
     * @return
     */
    public String deleteSend(String id) {
        //任务流程记录
        TaskSend taskSend = dao.getById(id);
        TaskNew taskNew = taskNewDao.getById(taskSend.getTaskId());
        SysUser user = userDao.getById(taskNew.getCreateUser());
        TaskLog taskLog = new TaskLog();
        taskLog.setProcesses("撤销任务单位");
        taskLog.setTableId(taskSend.getTaskId());
        taskLog.setTransactor(user.getName());
        taskLog.setTransactorTel(user.getMobile());
        taskLog.setDatetime(simdate.format(new Date()));
        taskLogService.save(taskLog);
        //删除的时候判断是否是最后一个未签收单位,如果是,将主任务状态改为已反馈
        //先查询当前任务的状态
        if ("0".equals(taskSend.getType())) {
            //如果当前任务是未签收,先将状态改为1待反馈
            taskSend.setType("1");
            dao.update(taskSend);
            //保存完后判断当前任务下的所有派发是否都已经签收
            //当前任务下派发的任务状态都是未签收的send没有数据,表示都已签收,改变主任务的type
            List<TaskSend> sendList = dao.queryByTaskIdAndType(id, "1");
            if (sendList.size() <= 0) {
                taskNew.setType("1");
                taskNewDao.update(taskNew);
                //如果其他任务都已反馈,那么状态小于2的只有一个,那么该任务是最后一个
                List<TaskSend> list = dao.queryByTaskIdAndType(id, "2");
                if (list.size() == 1) {
                    //将主任务状态改为已反馈
                    taskNew.setType("2");
                    taskNewDao.update(taskNew);
                }
            }
        }
        //如果当前任务是待反馈
        if ("1".equals(taskSend.getType())) {
            //先将状态改为已反馈
            taskSend.setType("2");
            dao.update(taskSend);
            //保存完后判断当前任务下的所有派发是否都已经签收
            //当前任务下派发的任务状态都是待反馈的send没有数据,表示都已反馈,改变主任务的type
            List<TaskSend> sendList = dao.queryByTaskIdAndType(taskSend.getTaskId(), "2");
            if (sendList.size() <= 0) {
                taskNew.setType("2");
                taskNewDao.update(taskNew);
            }
        }
        //如果不是最后一个未反馈的则直接删除
        dao.deleteById(id);

        return "200";
    }

    public List<TaskSend> findByTaskIdAndStatus(String sysId, String status) {
        return dao.findByTaskIdAndStatus(sysId, status);
    }

    /**
     * 返回县领导批转任务列表
     *
     * @param filter
     * @return
     */
    public List<TaskNew> queryEndorseList(TaskNewFilter filter) {
        return dao.queryEndorseList(filter);
    }


    /**
     * 添加任务办结情况
     *
     * @param filter
     * @return
     */
    public String updateSendEnd(TaskSendFilter filter) {
        TaskSend taskSend = dao.getById(filter.getSysId());
        taskSend.setType(filter.getType());
        taskSend.setScore(filter.getScore());
        //根据分数判断任务评价
        if ("100".equals(filter.getScore())) {
            taskSend.setComment("非常好");
        } else if ("60".equals(filter.getScore())) {
            taskSend.setComment("好");
        } else if ("30".equals(filter.getScore())) {
            taskSend.setComment("一般");
        } else {
            taskSend.setComment("差");
        }
        //如果任务逾期
        if ("0".equals(taskSend.getStatus())){
            taskSend.setScore("0");
        }
        dao.update(taskSend);

        //判断是否所有任务都已经完成
        List<TaskSend> sendList = dao.queryByTaskIdAndType(filter.getTaskId(), "3");
        if (sendList.size() <= 0) {
            List<TaskSend> taskSends = dao.findByTaskIdAndType(filter.getTaskId(), "4");
            if (taskSends.size() > 0) {
                //如果有任务未办结,主任务也未办结
                TaskNew taskNew = taskNewDao.getById(filter.getTaskId());
                taskNew.setType("4");
                taskNewDao.update(taskNew);
            } else {
                TaskNew taskNew = taskNewDao.getById(filter.getTaskId());
                taskNew.setType("3");
                taskNewDao.update(taskNew);
            }
        }
        return "200";
    }
}
